package com.hmdp.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // 缓存穿透
//        Shop shop = queryWithPassThrough(id);
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class,shopId -> getById(shopId), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 加锁,缓存击穿
//        Shop shop = queryWithMutex(id);

        // 逻辑过期
//        Shop shop = queryWithLogicExpire(id);
        if (shop == null) {
            return Result.fail("店铺暂无");
        }
        return Result.ok(shop);
    }

    public Shop queryWithLogicExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1.查找缓存,缓存不为空则返回
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
            LocalDateTime expireTime = redisData.getExpireTime();
            // 判断是否逻辑过期,没过期则返回
            Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
            if (expireTime.isAfter(LocalDateTime.now())) {
                return shop;
            }
        }
        // 2.缓存空值,则缓存不为null,返回null
        if (shopJson.equals("")) {
            return null;
        }
        // 3.缓存没有或者超出逻辑时间,查找数据库,进行缓存
        // 获取锁
        Shop shop = null;
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            Boolean flag = tryLockShop(lockKey);
            shop = saveByRedisData(id, 30L);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            unLock(lockKey);
        }
        return shop;
    }

    private Shop saveByRedisData(Long id, Long expireTime) {
        if (id == null || expireTime == null) {
            throw new RuntimeException("id或过期时间有误");
        }
        String key = CACHE_SHOP_KEY + id;
        // 查找店铺
        Shop shop = getById(id);
        if (shop == null) {
            // 缓存空值,做缓存穿透处理
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);

        }
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
        return shop;
    }

    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1.查找缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.缓存有,返回
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, new TypeReference<Shop>() {
            }, false);
            return shop;
        }
        // 缓存空值,则返回一个错误信息
        if (shopJson != null) {
            return null;
        }
        //用setIfAbsent上锁,防止线程直接访问数据库,缓存击穿
        String lockKey = LOCK_SHOP_KEY + id;
        Boolean flag = tryLockShop(lockKey);
        try {
            if (!flag.equals(true)) {
                // 没拿到锁,线程睡一下
                Thread.sleep(LOCK_SHOP_TTL);
            }
            // 拿到锁
            // 3.缓存没有,查数据库
            Shop shop = this.getById(id);
            if (shop == null) {
                // 4.数据库没有,缓存空值
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            } else {
                // 5.数据库有,查找数据返回,进行缓存
                shopJson = JSONUtil.toJsonStr(shop);
                stringRedisTemplate.opsForValue().set(key, shopJson, CACHE_SHOP_TTL, TimeUnit.MINUTES);
                return shop;
            }
        } catch (Exception e) {
            throw new RuntimeException("服务器有问题");
        } finally {
            //最后释放资源,解锁
            unLock(lockKey);
        }
    }

    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1.查找缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.缓存有,返回
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, new TypeReference<Shop>() {
            }, false);
            return shop;
        }
        // 缓存空值,则返回一个错误信息
        if (shopJson != null) {
            return null;
        }
        // 3.缓存没有,查数据库
        Shop shop = this.getById(id);
        if (shop == null) {
            // 4.数据库没有,缓存空值
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        } else {
            // 5.数据库有,查找数据返回,进行缓存
            shopJson = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(key, shopJson, CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return shop;
        }
    }

    private boolean tryLockShop(String key) {
        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return isLock.equals(true);
    }

    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
